<?php
namespace addons\ymyauexpress\library;

use fast\Http;
use think\Cache;
use think\Exception;

class Express
{
    protected $memberId = null;
    protected $password = null;
    protected $token = null;
    protected $error = null;
    private $token_api = "http://auth.auexpress.com/api/token";
    private $create_api = "http://aueapi.auexpress.com/api/AgentShipmentOrder/Create";
    private $brand_api = "http://aueapi.auexpress.com/api/Brand";
    private $upload_api = "http://aueapi.auexpress.com/api/PhotoIdUpload";
    private $print_api = "http://aueapi.auexpress.com/api/OrderLabelPrint";
    private $track_api = "http://aueapi.auexpress.com/api/ShipmentOrderTrack";

    public function __construct($memberId,$password)
    {
        $this->memberId = $memberId;
        $this->password = $password;
        $params = [
            'MemberId' => $this->memberId,
            'Password' => $this->password,
        ];
        $token = Cache::get($memberId.'_token');
        if($token){
            $this->token = $token;
        }else{
            $result = $this->postRequest($this->token_api,$params);
            if(isset($result['Token'])){
                $this->token = $result['Token'];
                Cache::set($memberId.'_token',$result['Token'],86000);
            }else{
                throw new Exception($result['Message'] ?? '代理号或密码不正确');
            }
        }

    }


    //创建订单
    public function create($order){
        $order['MemberId'] = (int) $this->memberId;
        $result = $this->postRequest($this->create_api,[$order]);
        if($result['Code'] == 0 && $result['ReturnResult'] == 'Success'){
            return $result['Message'];
        }else{
            $error = [];
            if(!empty($result['Errors'])){
                foreach ($result['Errors'] as $errors){
                    $error[] = $errors['Message'];
                }
                throw new Exception(implode(';',$error));
            }

            throw new Exception($result['Message'] ?? '接口请求失败');
        }
    }

    // 获取品牌
    public function brand(){
        $result = $this->getRequest($this->brand_api);
        if($result['Code'] == 0){
            return $result['brands'];
        }else{
            throw new Exception($result['Message'] ?? '接口请求失败');
        }
    }

    // 上传身份证
    public function upload($params){
        $result = $this->postRequest($this->upload_api,$params);
        if($result['Code'] == 0){
            return true;
        }else{
            return false;
        }
    }

    // 物流
    public function track($params){
        $url = $this->track_api.'?'.http_build_query($params);
        $result = $this->getRequest($url);
        if($result['Code'] == 0){
            return $result['TrackList'];
        }else{
            return [];
        }
    }

    // 打印
    public function print($params){
        $url = $this->print_api.'?'.http_build_query($params);
        $destDir = ROOT_PATH.'public/uploads/'.date('Ymd');
        if (!is_dir($destDir)) {
            @mkdir($destDir, 0755, true);
        }
        $filename = $destDir.'/'.$params['orderId'].'.pdf';
        $fp = fopen($filename, 'w+');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $this->token]);
        $ret = curl_exec($ch);
        curl_close($ch);
        if ($ret != false ) {
            return '/uploads/'.date('Ymd').'/'.$params['orderId'].'.pdf';
        }else{
            false;
        }

    }

    // post请求
    protected function postRequest($url,$params = []){
        $params = json_encode($params,JSON_UNESCAPED_UNICODE);
        $header = [
            'Content-Type: application/json',
            'Authorization: Bearer '.$this->token];
        $result = Http::post($url,$params,[
            CURLOPT_HTTPHEADER => $header,
        ]);
        return json_decode($result,true);
    }
    // get请求
    protected function getRequest($url,$params = []){
        $params = json_encode($params,JSON_UNESCAPED_UNICODE);
        $header = [
            'Content-Type: application/json',
            'Authorization: Bearer '.$this->token];
        $result = Http::get($url,$params,[
            CURLOPT_HTTPHEADER => $header,
        ]);
        return json_decode($result,true);
    }

    // file请求
    protected function fileRequest($url,$filename){



        $fp = fopen($filename, 'w+');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FILE, $fp);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Authorization: Bearer ' . $this->token]);
        dump(curl_exec($ch));
        curl_close($ch);
    }

}